package com.wujilee.wujileenetty.demos.web.netty.heima;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;


/**
 * @author liwuji
 * @date 2024/8/6
 * @desc netty 服务器基本案例
 **/
@Slf4j
public class HelloService {
    public static void main(String[] args) {

        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
//                        ch.pipeline().addLast(new StringDecoder());
                        log.info("服务端接收到了新的连接");
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                                  @Override
                                                  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                                      ByteBuf buffer = (ByteBuf) msg;
                                                      System.out.println(buffer.toString(Charset.defaultCharset()));
                                                  }

                                                  @Override
                                                  public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                                      super.channelActive(ctx);
                                                  }
                                              }
                        );

                    }
                })
                .bind(5672);
    }
}
